/*
  * Mirante Tecnologia
  * Copyright 2010, Mirante Informatica LTDA, 
  * and individual contributors as indicated by the @authors tag
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
package com.miranteinfo.seam.jsf.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

/**
 * Converter de cpf.
 * 
 * @author lucas lins
 *
 */
@BypassInterceptors
@Name("com.miranteinfo.CpfConverter")
@org.jboss.seam.annotations.faces.Converter
public class CpfConverter implements Converter {

	/**
	 * Formata o cpf passado de acordo com o padrao visual de um cpf
	 * 
	 * @param context
	 * @param component
	 * @param value
	 * @return cpf formatado
	 */
	public String getAsString(FacesContext context, UIComponent component, Object value) {
		if (value == null) return null;

		String cpf = value.toString();
		if (cpf.length() == 13) {
			return cpf;
		} else if (cpf.length() < 11) {
			return cpf;
		} else {
			return cpf.substring(0, 3) + "." + cpf.substring(3, 6) + "." + cpf.substring(6, 9) + "-" + cpf.substring(9, 11);
		}
	}

	/**
	 * Retorna o cpf sem sua formatacao.
	 * 
	 * @param context
	 * @param component
	 * @param value
	 * @return cpf sem formatacao
	 */
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		if(value == null || value.trim().equals("")) return null;
		return value.replace(".", "").replace("-", "").replace("/", "");
	}
}
